package itsm.isperp.module.controller.problem;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseProcessController;
import itsm.isperp.framework.web.domain.CountQuery;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.problem.ProbProblem;
import itsm.isperp.module.entity.project.ProjProject;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.problem.ProbProblemService;
import itsm.isperp.module.service.project.ProjProjectService;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-7-18
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("problem/problem")
public class ProbProblemController extends BaseProcessController<ProbProblem> {

	@Autowired
	protected ProbProblemService probProblemService;

	@Autowired
	protected AppDictService appDictService;

	@Autowired
	protected ProjProjectService projProjectService;

	@Override
	public String getProceessKey() {
		return "problemProcess";
	}

	@Override
	public ProbProblemService getService() {
		return probProblemService;
	}

	@Override
	public String getPageTitle() {
		return "变更";
	}

	@RequestMapping("view")
	public ModelAndView view(String id, HttpServletRequest req) {
		ModelAndView mv = this.getModelAndView();
		mv.addObject("model", this.getService().findOne(id));
		return mv;
	}

	@RequestMapping("newProblemEdit")
	public ModelAndView newProblemEdit(String id, HttpServletRequest req)
			throws Exception {
		ModelAndView mv = new ModelAndView("problem/problem/newProblemEdit");

		ProbProblem model = null;
		IUser user = ContextHolder.getLoginUser();
		if (!this.getService().exists(id)) {
			model = new ProbProblem();
			if (StringUtils.isEmpty(id)) {
				model.setId(HibernateUUIDGenerator.generate());
			}
			model.setRequester(user.getUsername());
			model.setRequesterName(user.getFullname());
			model.setRequestDate(new Timestamp(new Date().getTime()));

		} else {
			model = this.getService().findOne(id);
			if (StringUtils.isEmpty(model.getRequester())) {
				model.setRequester(user.getUsername());
				model.setRequesterName(user.getFullname());
				model.setRequestDate(new Timestamp(new Date().getTime()));

			}

			mv.addObject("modelEdit", true);

			ConfCiService confCiService = ContextHolder
					.getSpringBean("confCiService");

			Map<String, Object> ci = confCiService.findOneToMap(
					model.getCiId(), "name");

			if (MapUtils.isNotEmpty(ci))
				mv.addObject("ciName", ci.get("name"));

		}

		mv.addObject("currentUserId", user.getUsername());
		mv.addObject("currentUserName", user.getFullname());

		if (StringUtils.isEmpty(model.getSupporter())) {
			model.setSupporter(user.getUsername());
			model.setSupporterName(user.getFullname());
		}

		mv.addObject("model", model);

		// 紧急
		List<AppDict> urgencys = this.appDictService
				.findByType("PROBLEM_URGENCY");

		// 影响
		List<AppDict> effects = this.appDictService
				.findByType("PROBLEM_EFFECT");
		// 级别
		List<AppDict> prioritys = this.appDictService
				.findByType("PROBLEM_PRIORITY");

		List<ProjProject> projects = this.projProjectService.findAllPublished(
				"id", "name");

		mv.addObject("urgencys", urgencys);
		mv.addObject("effects", effects);
		mv.addObject("prioritys", prioritys);
		mv.addObject("projects", projects);

		return mv;
	}

	@RequestMapping("problemHandleEdit")
	public ModelAndView problemHandleEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("problem/problem/problemHandleEdit");

		ProbProblem model = this.getService().findOne(id);

		IUser u = ContextHolder.getLoginUser();

		model.setExecuteTime(new Timestamp(new Date().getTime()));
		model.setExecuter(u.getUsername());
		model.setExecuterName(u.getFullname());

		mv.addObject("model", model);

		return mv;

	}

	@RequestMapping("analysisEdit")
	public ModelAndView analysisEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("problem/problem/analysisEdit");

		ProbProblem model = this.getService().findOne(id);
		mv.addObject("model", model);

		return mv;

	}

	@RequestMapping("assignEdit")
	public ModelAndView assignEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("problem/problem/assignEdit");

		ProbProblem model = this.getService().findOne(id);
		mv.addObject("model", model);

		return mv;

	}

	@RequestMapping("acceptEdit")
	public ModelAndView acceptEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("problem/problem/acceptEdit");

		ProbProblem model = this.getService().findOne(id);
		mv.addObject("model", model);

		return mv;

	}

	@RequestMapping("planEdit")
	public ModelAndView planEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("problem/problem/planEdit");

		ProbProblem model = this.getService().findOne(id);
		mv.addObject("model", model);

		return mv;

	}

	// 交付评审
	@RequestMapping("reviewEdit")
	public ModelAndView reviewEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("problem/problem/reviewEdit");

		ProbProblem model = this.getService().findOne(id);
		mv.addObject("model", model);

		return mv;

	}

	// 制定措施
	@RequestMapping("measureEdit")
	public ModelAndView measureEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("problem/problem/measureEdit");

		ProbProblem model = this.getService().findOne(id);
		mv.addObject("model", model);

		return mv;

	}

	@RequestMapping("approvalEdit")
	public ModelAndView approvalEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("problem/problem/approvalEdit");

		ProbProblem model = this.getService().findOne(id);
		mv.addObject("model", model);

		return mv;

	}

	// 协调
	@RequestMapping("coordinateEdit")
	public ModelAndView coordinateEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("problem/problem/coordinateEdit");

		ProbProblem model = this.getService().findOne(id);
		mv.addObject("model", model);

		return mv;

	}

	// 识别
	@RequestMapping("recognitionEdit")
	public ModelAndView recognitionEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("problem/problem/recognitionEdit");

		ProbProblem model = this.getService().findOne(id);
		mv.addObject("model", model);

		return mv;

	}

	// 升级
	@RequestMapping("upgradeEdit")
	public ModelAndView upgradeEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("problem/problem/upgradeEdit");

		ProbProblem model = this.getService().findOne(id);
		mv.addObject("model", model);

		return mv;

	}

	@RequestMapping("closeEdit")
	public ModelAndView closeEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("problem/problem/closeEdit");

		ProbProblem model = this.getService().findOne(id);
		mv.addObject("model", model);

		return mv;

	}
	@RequestMapping("statusProcessManage")
	public ModelAndView statusProcessManage() {
		return this.getModelAndView();
	}
	
	@RequestMapping("statusProcessMenu")
	@ResponseBody
	public ITreeNode[] statusProcessMenu() {
		return this.createStatusProcessCountQuery().getTreeNodes();

	}
	protected CountQuery createStatusProcessCountQuery() {
		CountQuery cq = this.createDefaultCountQuery();

		List<AppDict> dicts = this.appDictService.findByType("PROBLEM_STATUS");

		for (AppDict d : dicts) {
			cq.addCountFilter(d.getName(), true, " a.status='" + d.getName()
					+ "' ");
		}

		return cq;
	}
	@RequestMapping("listStatusProcessDetail")
	@ResponseBody
	public PageResponse<Map<String, Object>> listStatusProcessDetail(
			JqGridRequest request, HttpServletRequest req) {
		return this.getListDetail(createStatusProcessCountQuery(), request, req);
	}
	
  @RequestMapping("doUpdateTime")
  @ResponseBody
  public String doUpdateTime(HttpServletRequest req) throws ParseException {
    String code = req.getParameter("pr_code");
    String createTime = req.getParameter("pr_createTime");
    // String responseTime=req.getParameter("responseTime");
    // String arriveTime=req.getParameter("arriveTime");
    // String solveTime=req.getParameter("solveTime");
    String closeTime = req.getParameter("closeTime");
    try {
      SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
      Date createDate = sFormat.parse(createTime);
      Date closeDate = null;
      if (StringUtils.isNotEmpty(closeTime)) {
        closeDate = sFormat.parse(closeTime);
      }

      this.getService().doUpdateTime(code,createDate);
      return "成功";
    } catch (Exception e) {
      return "异常";
    }

  }
  
  @RequestMapping("addKnowledge")
  @ResponseBody
  public boolean addKnowledge(String id,HttpServletRequest req){
	  JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
	  String sql = "UPDATE prob_problem SET add_knowledge = 1 WHERE id = '"+id+"'";
	  jdbcTemplate.execute(sql);
	  return true;
  }
  
  @RequestMapping("checkKnowledge")
  @ResponseBody
  public boolean checkKnowledge(String id,HttpServletRequest req){
	  JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
	  ProbProblem model = this.get(id);
	  if("1".equals(model.getAddKnowledge())){
			String sql = "SELECT a.id FROM kng_knowledge_item a LEFT JOIN bpm_process_relation b ON a.id = b.`to_id` " +
					"LEFT JOIN prob_problem c ON c.`id`=b.`from_id` " +
					"WHERE c.`id`=?";
			int size = jdbcTemplate.queryForList(sql, id).size();
			if (size > 0) {
				return true;
			}else{
				return false;
			}
	  }
	  return true;
  }
	
}
